package com.chukun.concurrency.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * countDownLatch的基本使用
 */
@Slf4j
public class CountDownLatchOperator {

    //总共的线程数
    private final static int totalCount = 20;

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(totalCount);

        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i=0;i<totalCount;i++){
            final int count=i;
            executorService.execute(()->{
                try {
                    test(count);
                }catch (Exception e){
                    log.error("error :",e);
                }finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("interrupted ",e);
        }
        executorService.shutdown();
        log.info("finish");
    }

    public static void test(int i){
        log.info("threadNum :{}",i);
    }
}
